package org.example.votezq.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.votezq.entity.Items;
import org.example.votezq.entity.Result;
import org.example.votezq.entity.Vote;
import org.example.votezq.mapper.VoteMapper;
import org.example.votezq.service.BizException;
import org.example.votezq.service.IVoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiaoYan
 * @since 2025-09-20
 */
@RestController
@RequestMapping("vote")
public class VoteController {

    @Autowired
    VoteMapper voteMapper;

    @RequestMapping("list")
    public Page<Vote> list(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size){
        // 构建分页对象
        Page<Vote> pg = Page.of(page, size);
        pg = voteMapper.selectPage(pg, null);
        return pg;
    }

    @Autowired
    IVoteService voteService;

    @RequestMapping("add")
    public Result add(@RequestBody @Valid Vote vote, Errors errors){
        System.out.println("接收到的投票数据: " + vote); // 调试日志

        // 添加自定义验证
        if(vote.getStartDate() != null && vote.getEndDate() != null &&
                vote.getStartDate().isAfter(vote.getEndDate())){
            errors.rejectValue("endDate", "dateError", "结束时间不能早于开始时间");
        }

        if(vote.getItems()!=null){
            for (int i = 0; i < vote.getItems().size(); i++) {
                Items item = vote.getItems().get(i);
                if(item.getIname() == null || item.getIname().isBlank()){
                    errors.rejectValue("items", "itemEmpty", "第"+(i+1)+"个选项没有输入内容");
                }
            }
        }

        if(errors.hasErrors()){
            System.out.println("验证错误: " + errors.getAllErrors()); // 调试日志
            throw new BizException("提交数据错误", errors.getAllErrors());
        }
        voteService.create(vote);
        return Result.ok("添加投票题目成功", null);
    }
}